<template>
  <van-address-list
    :list="addressList"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    :add-button-text="
      route.query.isCart === '1' || route.query.goodsId
        ? '生成订单'
        : '新增地址'
    "
    v-model="checkedAddress"
  />
</template>

<script setup>
import { getAddressList } from "@/api/address";
import router from "@/router";
import { useRoute } from "vue-router";
import { ref, onMounted } from "vue";
// 路由实例
let route = useRoute();
// 地址列表
let addressList = ref([]);

let checkedAddress = ref(null);

// 进入页面 获取数据
onMounted(async () => {
  // 获取地址列表
  let arr = (await getAddressList({ limit: 10, page: 1 })).data.list;
  // 把后端数据 构造为组件接收的数据
  addressList.value = arr.map((item) => {
    return {
      id: item.id,
      name: item.name,
      tel: item.phone,
      address: item.province + item.city + item.town,
      isDefault: item.is_default === 1,
    };
  });
});

// 点击底部按钮
let onAdd = () => {
  // 判断是新增地址  还是 生成订单
  if (route.query.isCart) {
    // 从购物车 来的  点击跳转至 生成订单页面
    router.push(
      `/create-order?checkedGoods=${route.query.checkedGoods}&addressId=${checkedAddress.value}`
    );
    //
  } else if (route.query.goodsId) {
    // 从 商品详情直接购买的   传递商品id
    router.push(
      `/create-order?addressId=${checkedAddress.value}&goodsId=${route.query.goodsId}`
    );
  } else {
    router.push("/edit-address");
  }
};

// 点击新增 跳转至 新增
let onEdit = (item) => {
  router.push(`/edit-address?id=${item.id}`);
};
</script>

